The program's goal is to roll two dice until both of them equal 6. When I used && in the while statement it stops after one dice equals 6. Why is that? Shouldn't && test the first condition then if it is correct test the second?
while ((diceOne != 6) || (diceTwo != 6)) {
diceOne = numberGeneration.Next(1, 7);
diceTwo = numberGeneration.Next(1, 7);
attempt = ++attempt;
Console.WriteLine("Your first dice is: " + diceOne + " your second dice is: " + diceTwo);
Console.WriteLine("Press any button to continue");
Console.ReadKey();
}
Console.WriteLine("It took you " + attempt);
Console.WriteLine("Press any key to continue");
Console.ReadKey();
It stops because you break the condition of one dice being different from 6.
while ((diceOne != 6) && (diceTwo != 6))
While will execute while both conditions are true.
I agree with @Pedro, also you can use break statement in the while(true) loop and stop the loop when both of dices are equal to 6:
while (true) {
diceOne = numberGeneration.Next(1, 7);
diceTwo = numberGeneration.Next(1, 7);
attempt = ++attempt;
Console.WriteLine("Your first dice is: " + diceOne + " your second dice is: " + diceTwo);
Console.WriteLine("Press any button to continue");
Console.ReadKey();
if (diceOne == 6 && diceTwo == 6) break;
}
Console.WriteLine("It took you " + attempt);
Console.WriteLine("Press any key to continue");
Console.ReadKey();
Note that the while loop condition is the necessary and sufficient condition to continue the loop. (diceOne != 6) && (diceTwo != 6)) says that "both dice are not 6". When both dice are not 6, you certainly want to continue the loop, so it's a sufficient condition, but this is not a necessary condition. When else would you want to continue the loop? When one dice is 6 and one dice isn't!
The necessary and sufficient condition to continue the loop is that at least one dice is not 6, which is what the || expresses.
Other users already have explained you why it's not working. I may suggest to modify the while statement like this:
while (!(diceOne == 6 && diceTwo == 6))